import React from 'react';
import {Spin, Card, Button, Row, Col, Form} from 'antd';
import PropTypes from 'prop-types';
import routes from './routes';
import {FORM_OPTIONS, FORM_ROW_OPTIONS} from '../constants';
import {updateApplyReport, getDetail} from './api';
import TextInput from 'Shared/components/TextInput';
import SearchInput from 'Shared/components/SearchInput';
import ProductCategorySelectPanel from './ProductCategorySelectPanel';
import WrappedDatePicker from '../common/WrappedDatePicker';
import DutyUnitSelectPanel from './DutyUnitSelectPanel';
import {injectIntl} from './intl';
import WrappedSelect from '../common/WrappedSelect';
import LocalizeInputNumber from '../common/LocalizeInputNumber';
import styles from './style.css';
import Return from '../common/Return';
import {newOrUpdateOrderValidator} from './validator';
const FormItem = Form.Item;

class UpdatePanel extends React.PureComponent {
    state = {
        loading: false,
        hasOperat: false,
        isValidate: false,
        data: {},
    }
    componentDidMount() {
        const id = this.props.id;
        this.setState({loading: true});
        getDetail(id)
            .then(res => {
                if(res.ok)
                    this.setState({
                        loading: false,
                        data: res.data,
                    });
                else
                    this.setState({loading: false});
            });
    }
    componentWillUnmount() {
        this.isunmount = true;
    }
    onChange = (value, name) => {
        const data = Object.assign({}, this.state.data, {
            [name]: value
        });
        this.setState({
            data,
            hasOperat: true
        });
    }
    onClickOkOnPopconfirm = () => {
        this.props.onCancel();
    }
    onSubmit = () => {
        const data = this.state.data;
        const isValid = newOrUpdateOrderValidator(data);
        if(!isValid) {
            this.setState({
                isValidate: true
            });
            return;
        }
        const condition = {
            brandId: data.brandId,
            dutyUnitId: data.dutyUnitId,
            productCategoryId: data.productCategoryId,
            mileage: data.mileage,
            date: data.date,
            startTime: data.startTime,
            endTime: data.endTime,
            remark: data.remark,
            rowVersion: data.rowVersion,
        };
        this.setState({loading: true});
        updateApplyReport(this.props.id, condition).then(res => {
            if(res.ok)
                this.props.successReturn();
            if(!this.isunmount)
                this.setState({loading: false});
        });
    }
    render() {
        const {formatMessage} = this.props.intl;
        const {data, isValidate, loading} = this.state;
        const {brands} = this.props.initEnumData;
        if(brands.length === 1 && !this.props.id) {
            data.brandId = brands[0].value;
            data.brandName = brands[0].text;
        }
        return (
            <div className="form-standard">
                <Spin spinning={this.state.loading}>
                    <Card title={formatMessage({
                        id: 'updatePanel.column.common',
                        defaultMessage: '供应商担保期信息'
                    })}>
                        <Form>
                            <Row>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'updatePanel.operation.code',
                                        defaultMessage: '编号'
                                    })}{...FORM_OPTIONS.item}>
                                        {data.code}
                                    </FormItem>
                                </Col>
                                {brands.length !== 1 && <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'updatePanel.operation.brandName',
                                        defaultMessage: '品牌'
                                    })}{...FORM_OPTIONS.item} validateStatus={isValidate && !data.brandId ? 'error' : null} required>
                                        <WrappedSelect
                                            disabled={true}
                                            name="brandId"
                                            value={data.brandId}
                                            options={brands}
                                            onChange={this.onChange}/>
                                    </FormItem>
                                </Col>}
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'updatePanel.operation.dutyUnitId',
                                        defaultMessage: '供应商'
                                    })} {...FORM_OPTIONS.item} validateStatus={isValidate && !data.dutyUnitId ? 'error' : null} required>
                                        {data.dutyUnitCode === undefined ? '' : `(${data.dutyUnitCode})${data.dutyUnitName}`}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'updatePanel.data.productCategoryId',
                                        defaultMessage: '车型'
                                    })}{...FORM_OPTIONS.item} validateStatus={isValidate && !data.productCategoryId ? 'error' : null} required>
                                        {data.productCategoryCode === undefined ? '' : `(${data.productCategoryCode})${data.productCategoryName}`}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'updatePanel.operation.mileage',
                                        defaultMessage: '担保里程（KM）'
                                    })} {...FORM_OPTIONS.item} validateStatus={isValidate && !data.mileage ? 'error' : null} required>
                                        <LocalizeInputNumber
                                            name="mileage"
                                            value={data.mileage}
                                            onBlur={this.onChange} />
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'updatePanel.operation.date',
                                        defaultMessage: '担保期限（月）'
                                    })} {...FORM_OPTIONS.item} validateStatus={isValidate && !data.date ? 'error' : null} required>
                                        <LocalizeInputNumber
                                            name="date"
                                            value={data.date}
                                            onBlur={this.onChange} />
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'updatePanel.operation.startTime',
                                        defaultMessage: '开始时间'
                                    })} {...FORM_OPTIONS.item} validateStatus={isValidate && !data.startTime ? 'error' : null} required>
                                        <WrappedDatePicker
                                            name="startTime"
                                            value={data.startTime}
                                            onChange={this.onChange}/>
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'updatePanel.operation.endTime',
                                        defaultMessage: '结束时间'
                                    })} {...FORM_OPTIONS.item} validateStatus={isValidate && (!data.endTime || data.endTime < data.startTime) ? 'error' : null} required>
                                        <WrappedDatePicker
                                            name="endTime"
                                            value={data.endTime}
                                            onChange={this.onChange}/>
                                    </FormItem>
                                </Col>
                            </Row>
                            <Row className="row-margin">
                                <Col>
                                    <FormItem label={formatMessage({
                                        id: 'updatePanel.text.remark',
                                        defaultMessage: '备注'
                                    })} {...FORM_ROW_OPTIONS.item}>
                                        <TextInput
                                            type="textarea"
                                            name="remark"
                                            value={data.remark}
                                            onBlur={this.onChange} />
                                    </FormItem>
                                </Col>
                            </Row>
                        </Form>
                    </Card>
                    <Card className={styles.optionBtn}>
                        <Button
                            type="primary"
                            onClick={this.onSubmit}
                            loading={loading}>
                            {formatMessage({
                                id: 'updatePanel.operation.onSubmit',
                                defaultMessage: '保存'
                            })}
                        </Button>
                    </Card>
                </Spin>
                <div className="page-toolbar">
                    <Return
                        disabled={this.state.loading}
                        onConfirm={this.onClickOkOnPopconfirm}
                        showWarning={this.state.hasOperat} />
                </div>
            </div>
        );
    }
}

UpdatePanel.propTypes = {
    successReturn: PropTypes.func.isRequired,
    onCancel: PropTypes.func.isRequired,
    onSelect: PropTypes.func.isRequired,
    history: PropTypes.object,
    id: PropTypes.string,
    intl: PropTypes.object,
};

import {connect} from 'react-redux';
import {
    tableSearch,
    saveQueryDealer
} from './actions';
import {createSelector} from 'reselect';

const getinitEnumData = createSelector(
    state => state.getIn(['page', 'domainData', 'init']),
    init => {
        const initData = init.toJS();
        const brands = initData.brands ? initData.brands.map(item => ({
            text: `(${item.code})${item.name}`,
            value: item.id
        })) : [];
        return {
            brands,
        };
    }
);
const mapStateToProps = state => ({
    initEnumData: getinitEnumData(state),
});
const mapDispatchToProps = (dispatch, props) => ({
    onSelect: data => dispatch(saveQueryDealer(data)),
    successReturn: () => {
        dispatch(tableSearch());
        props.history.push(routes.query.url());
    },
    onCancel: () => {
        props.history.push(routes.query.url());
    },
});
export default connect(mapStateToProps, mapDispatchToProps)(injectIntl(UpdatePanel));
